package com.jmu.edu.IMApplication.fragment;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;
import android.widget.Toast;

import com.google.android.flexbox.FlexboxLayout;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jmu.edu.IMApplication.MyApplication;
import com.jmu.edu.IMApplication.R;
import com.jmu.edu.IMApplication.event.RefreshTagListEvent;
import com.jmu.edu.IMApplication.net.bean.UserTag;
import com.jmu.edu.IMApplication.utils.HttpUtil;
import com.jmu.edu.IMApplication.utils.ViewUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.im.android.api.model.UserInfo;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class ShowTagFragment extends Fragment {
    private static final String TAG = "showTag";
    private TabLayout tabLayout;
    private MaterialButton hobbyButton, habitButton, hatedHabitButton, backButton;
    private FlexboxLayout hobbyFlexBox, habitFlexBox, hatedHabitFlexBox;
    private List<UserTag> hobbyList, habitList, hatedHabitList;
    private UserInfo userInfo;
    private String backTag;
    private boolean isNewUser = true;

    public void setUserInfo(UserInfo userInfo) {
        this.userInfo = userInfo;
        Log.d(TAG, "setUserInfo: uid:" + userInfo.getUserID());
    }

    public void setNewUser(boolean newUser) {
        isNewUser = newUser;
    }

    public ShowTagFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_show_tag, container, false);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        loadData();

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            setArguments(null);
        } else {
            loadData();
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }
        }
    }

    private void initView() {
        hobbyButton = getView().findViewById(R.id.fragment_show_tag_hobby);
        habitButton = getView().findViewById(R.id.fragment_show_tag_habit);
        hatedHabitButton = getView().findViewById(R.id.fragment_show_tag_habit_hated);
        backButton = getView().findViewById(R.id.fragment_show_tag_back);
        tabLayout = getView().findViewById(R.id.fragment_show_tag_tab_layout);
        initListener();
        hobbyFlexBox = getView().findViewById(R.id.fragment_show_tag_hobby_flexBox);
        habitFlexBox = getView().findViewById(R.id.fragment_show_tag_habit_flexBox);
        hatedHabitFlexBox = getView().findViewById(R.id.fragment_show_tag_habit_hated_flexBox);
        initTabLayout();


    }

    private void initTabLayout() {
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("爱好");
        arrayList.add("生活习惯");
        arrayList.add("厌恶");

        for (String string : arrayList) {
            TabLayout.Tab tab = tabLayout.newTab();
            tab.setText(string);
            tabLayout.addTab(tab);
        }
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                handleTabOnSelected(tab.getText().toString());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    private void handleTabOnSelected(String tab) {
        switch (tab) {
            case "爱好":
                hobbyFlexBox.setVisibility(View.VISIBLE);
                hobbyButton.setVisibility(View.VISIBLE);
                habitFlexBox.setVisibility(View.GONE);
                habitButton.setVisibility(View.GONE);
                hatedHabitFlexBox.setVisibility(View.GONE);
                hatedHabitButton.setVisibility(View.GONE);
                break;
            case "生活习惯":
                hobbyFlexBox.setVisibility(View.GONE);
                hobbyButton.setVisibility(View.GONE);
                habitFlexBox.setVisibility(View.VISIBLE);
                habitButton.setVisibility(View.VISIBLE);
                hatedHabitFlexBox.setVisibility(View.GONE);
                hatedHabitButton.setVisibility(View.GONE);
                break;
            case "厌恶":
                hobbyFlexBox.setVisibility(View.GONE);
                hobbyButton.setVisibility(View.GONE);
                habitFlexBox.setVisibility(View.GONE);
                habitButton.setVisibility(View.GONE);
                hatedHabitFlexBox.setVisibility(View.VISIBLE);
                hatedHabitButton.setVisibility(View.VISIBLE);
                break;
        }
    }


    private void loadData() {
        ViewUtils.addBackListenerForHide(getView(), backButton);

        if (getArguments() != null) {
            backTag = getArguments().getString("backTag", null);
            // 这个变量是用来判断是否需要重新加载数据的
            isNewUser = getArguments().getInt("isNewUser", 1) == 1;
        } else {
            isNewUser = false;
        }

        // 如果当前界面要加载的是新用户，说明需要重新加载数据，那么此时全部都应该设置为false, 当数据加载完毕以后, 判断该展示界面是否是自己的界面，如果是自己的界面那么才允许点击
        if (isNewUser) {
            hobbyButton.setClickable(false);
            habitButton.setClickable(false);
            hatedHabitButton.setClickable(false);
        }

        if (isNewUser) {
            Log.d(TAG, "loadData: isNewUser");
            RequestBody requestBody = RequestBody.create(null, "");
            String url = HttpUtil.URL_GET_USER_TAG + "?username=" + userInfo.getUserName();
            Request request = new Request.Builder().url(url).post(requestBody).build();
            MyApplication.getClient().newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "onFailure: ", e);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String json = response.body().string();
                    TypeToken<List<UserTag>> typeToken = new TypeToken<List<UserTag>>() {
                    };
                    //将json数据转化为实体类
                    List<UserTag> tagList = new Gson().fromJson(json, typeToken.getType());
                    //重置三个列表
                    if (hobbyList == null) {
                        hobbyList = new ArrayList<>();
                    } else {
                        hobbyList.clear();
                    }
                    if (habitList == null) {
                        habitList = new ArrayList<>();
                    } else {
                        habitList.clear();
                    }
                    if (hatedHabitList == null) {
                        hatedHabitList = new ArrayList<>();
                    } else {
                        hatedHabitList.clear();
                    }
                    // 如果为空说明该用户还没有选取任何的标签
                    if (tagList != null) {
                        // 将tagList按照类别、喜好划分为三个子表
                        for (UserTag userTag : tagList) {
                            if (userTag.getType() == 1) {
                                hobbyList.add(userTag);
                            } else {
                                if (userTag.getLike() == 1) {
                                    habitList.add(userTag);
                                } else {
                                    hatedHabitList.add(userTag);
                                }
                            }
                        }
                        tagList.clear();
                    }
                    // 在主线程中刷新标签
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            initFlexBox();
                        }
                    });


                }
            });
        }


    }

    private void initFlexBox() {
        Log.d(TAG, "initFlexBox: start");

        // 如果是自己的界面，那么可以点击
        if (userInfo.getUserID() == MyApplication.getUser().getUserID()) {
            hobbyButton.setClickable(true);
            habitButton.setClickable(true);
            hatedHabitButton.setClickable(true);
        }

        hobbyFlexBox.removeAllViews();

        loadFlexBox(hobbyList, hobbyFlexBox);

        habitFlexBox.removeAllViews();

        loadFlexBox(habitList, habitFlexBox);
        hatedHabitFlexBox.removeAllViews();

        loadFlexBox(hatedHabitList, hatedHabitFlexBox);
    }

    @Subscribe
    public void onRefreshTagListEvent(RefreshTagListEvent event) {
        Log.d(TAG, "onRefreshTagListEvent: 收到事件");

        switch (event.getType()) {
            case "hobby":
                hobbyList.clear();
                hobbyList = event.getTagList();
                Log.d(TAG, "onRefreshTagListEvent: "+hobbyList);
                hobbyFlexBox.removeAllViews();
                loadFlexBox(event.getTagList(), hobbyFlexBox);
                break;
            case "habit":
                habitList.clear();
                habitList = event.getTagList();
                habitFlexBox.removeAllViews();
                loadFlexBox(event.getTagList(), habitFlexBox);
                break;
            case "hatedHabit":
                hatedHabitList.clear();
                hatedHabitList = event.getTagList();
                hatedHabitFlexBox.removeAllViews();
                loadFlexBox(event.getTagList(), hatedHabitFlexBox);
                break;
            default:
                break;
        }
    }

    private void loadFlexBox(List<UserTag> tagList, FlexboxLayout tagFlexBox) {
        for (int i = 0; i < tagList.size(); i++) {
            Log.d(TAG, "tag: " + tagList.get(i) + ",i: " + i);
            tagFlexBox.addView(ViewUtils.getTagItemView(getLayoutInflater(), tagList.get(i).getTag(), i, getResources(), false));
        }

    }


    private void initListener() {
        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<Integer, Integer> chosenUserTagMap = new HashMap<>();
                String title = "";
                String type = "";
                switch (v.getId()) {
                    case R.id.fragment_show_tag_hobby:
                        title = "请选择您的兴趣爱好";
                        type = "hobby";
                        for (UserTag userTag : hobbyList) {
                            chosenUserTagMap.put(userTag.getTagId(), userTag.getUserTagId());
                        }
                        break;
                    case R.id.fragment_show_tag_habit:
                        title = "请选择您的生活习惯";
                        type = "habit";
                        for (UserTag userTag : habitList) {
                            chosenUserTagMap.put(userTag.getTagId(), userTag.getUserTagId());
                        }
                        break;
                    case R.id.fragment_show_tag_habit_hated:
                        title = "请选择您讨厌的标签";
                        type = "hatedHabit";
                        for (UserTag userTag : hatedHabitList) {
                            chosenUserTagMap.put(userTag.getTagId(), userTag.getUserTagId());
                        }
                        break;
                    default:
                        break;
                }
                Log.d(TAG, "onClick: map\n" + chosenUserTagMap);
                Log.d(TAG, "\nonClick: hobby\n"+hobbyList);
                Log.d(TAG, "\nonClick: habit\n"+habitList);
                Log.d(TAG, "\nonClick: hated\n"+hatedHabitList);
                String tag = "selectTag";
                SelectTagFragment selectTagFragment = (SelectTagFragment) MyApplication.fragmentManager.findFragmentByTag(tag);
                if (selectTagFragment == null) {
                    selectTagFragment = new SelectTagFragment();
                }
                selectTagFragment.setType(type);
                selectTagFragment.setTitle(title);
                selectTagFragment.setDescription("");
                // 这个先待定
                selectTagFragment.setUsername(userInfo.getUserName());
                // 设置被选中的tag
                selectTagFragment.setChosenUserTagMap(chosenUserTagMap);
                ViewUtils.hideFragment(ShowTagFragment.this, selectTagFragment, tag, R.anim.from_right, R.anim.out_left);

            }
        };
        hobbyButton.setOnClickListener(clickListener);
        habitButton.setOnClickListener(clickListener);
        hatedHabitButton.setOnClickListener(clickListener);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (backTag == null) {
                    ViewUtils.hideFragment(ShowTagFragment.this, R.anim.from_right, R.anim.out_right);
                } else {
                    Fragment fragment = MyApplication.fragmentManager.findFragmentByTag(backTag);
                    ViewUtils.hideFragment(ShowTagFragment.this, fragment, backTag, R.anim.from_left, R.anim.out_right);
                }
                EventBus.getDefault().unregister(this);
            }
        });

    }


}